﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ECMessageQueue;
using ECLogger;
using FESSC_MESSAGE;
using System.Threading;

namespace FESSC_WORKBENCH_SERVER
{
    public class MQWorker
    {
        public MQServer mqserver;
        public Logger log;
        public Thread tMessageLoop;

        public MQWorker(Logger logger)
        {
            log = logger;
            mqserver = new MQServer(log);
            mqserver.runSender();
        }

        public void getMessageLoop()
        {
            while (true)
            {
                try
                {
                    var mqmsg = mqserver.getMessage();
                    Msg msg = new Msg(mqmsg.content);
                    string msgroot = msg.getRootName();
                    switch (msgroot)
                    {
                        case "rq":
                            string operation = msg.getValueByXpath("/rq/header/operation");
                            OperationDict.rqOps[operation](mqmsg);
                            break;
                        case "rs":
                            break;
                        default:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.ToString());
                }
            }
        }

        public void startMessageLoop()
        {
            tMessageLoop = new Thread(new ThreadStart(getMessageLoop));
            tMessageLoop.Start();
        }

        public void stopMessageLoop()
        {
            tMessageLoop.Abort();
        }

        public void close()
        {
            stopMessageLoop();
            mqserver.close();
        }
    }
}
